<template>
  <div class="sku">
    <c-form
      v-model="form"
      :data="formData"
      :col="{ labelCol: { style: 'width: 90px;text-align: right;' } }"
    >
      <template v-for="item in formData" v-slot:[item.prop]>
        <a-radio-group
          v-model="form[item.prop]"
          @change="
            val => {
              attrChange(item.prop, val);
            }
          "
          :key="item.prop"
        >
          <template v-for="i in getAttrs(item.prop)">
            <a-radio-button
              :value="i"
              :class="[
                checkAttrAble[item.prop].indexOf(i) === -1 ? 'disabled' : ''
              ]"
              :key="i"
            >
              {{ i }}
            </a-radio-button>
          </template>
        </a-radio-group>
      </template>
    </c-form>
  </div>
</template>

<script>
import { uniq, pick, isEqual } from "lodash";
import { getsimilarquotation } from "@/api/quotation";
import { debounce } from "@/util/common";

export default {
  props: {
    //   报价详情id
    id: {
      type: Number,
      default: undefined
    },
    //   报价详情
    quotationDetail: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      form: {
        brand: undefined,
        spec: undefined,
        material: undefined,
        other: undefined,
        warehouseShortName: undefined
      },
      formData: [
        {
          label: "品牌",
          prop: "brand",
          slot: "brand"
        },
        {
          label: "规格",
          prop: "spec",
          slot: "spec"
        },
        {
          label: "材质",
          prop: "material",
          slot: "material"
        },
        {
          label: "其他",
          prop: "other",
          slot: "other"
        },
        {
          label: "仓库",
          prop: "warehouseShortName",
          slot: "warehouseShortName"
        }
      ],
      // 所有可选项
      checkAttrs: {
        brand: [],
        spec: [],
        material: [],
        other: [],
        warehouseShortName: []
      },
      // 可选项
      checkAttrAble: {
        brand: [],
        spec: [],
        material: [],
        other: [],
        warehouseShortName: []
      },
      // 选中商品
      checkProduct: {}
    };
  },
  computed: {
    // 计算可选属性
    getAttrs() {
      return prop => {
        let res = [];
        if (this.quotationDetail.quotationDetailList) {
          res = JSON.parse(
            JSON.stringify(this.quotationDetail.quotationDetailList)
          );
          res = res.filter(i => i[prop]);
          res = res.map(i => i[prop]);
          this.checkAttrs[prop] = uniq(res);
          // res长度为0，则不需要显示prop对应的参数
          if (res.length === 0) {
            this.formData.forEach((item, index) => {
              if (item.prop === prop) {
                this.$set(this.formData, index, {
                  ...item,
                  hidden: true
                });
              }
            });
          }
        }
        return uniq(res);
      };
    }
  },
  methods: {
    // 查询相似报价
    getSimilarQuotation: debounce(function() {
      getsimilarquotation({
        quotationDetailId: this.checkProduct.id
      }).then(res => {
        this.$emit("getSimilarity", res);
      });
    }),
    //   切换商品
    attrChange(prop) {
      this.checkAttrAble = {
        brand: [],
        spec: [],
        material: [],
        other: [],
        warehouseShortName: []
      };
      this.filtrateQuotationDetail(prop).then(() => {
        // 查询相似商品
        this.getSimilarQuotation();
        // 查询选中商品的信息，并传递出去
        let params = this.getProductData();
        this.$emit("change", params);
      });
    },
    // 查询选中商品的信息
    getProductData() {
      let list = this.quotationDetail.quotationDetailList;
      let res;
      for (let i = 0; i < list.length; i++) {
        // 提取需要进行对比的key，组成新对象
        let obj = pick(list[i], [
          "brand",
          "spec",
          "material",
          "other",
          "warehouseShortName"
        ]);
        let other = Object.assign({}, this.form);
        // 删除值为undefined的key
        for (const key in other) {
          if (!other[key]) delete other[key];
        }
        for (const key in obj) {
          if (!obj[key]) delete obj[key];
        }
        // 对比当前选中商品与该商品是否相等（品牌、规格、材质、其他、仓库）
        if (isEqual(other, obj)) {
          res = list[i];
          break;
        }
      }
      this.checkProduct = res;
      return res;
    },
    filtrateQuotationDetail(prop, val) {
      return new Promise(resolve => {
        this.checkAttrAble[prop] = val ? val : this.form[prop];
        // 筛选出有相同prop值的子商品
        // console.log(prop, val);
        let ables = this.quotationDetail.quotationDetailList.filter(
          item => item[prop] === (val ? val : this.form[prop])
        );
        // console.log("ables", ables);
        this.filtrateAttrItem(ables, prop).then(() => {
          resolve();
        });
      });
    },
    filtrateAttrItem(data, prop) {
      return new Promise(resolve => {
        // 根据筛选出的子商品筛选出其他prop的可选项
        let attrs = [
          "brand",
          "spec",
          "material",
          "other",
          "warehouseShortName"
        ];
        attrs.splice(attrs.indexOf(prop), 1);
        attrs.forEach(item => {
          this.checkAttrAble[item] = uniq(
            this.checkAttrAble[item].concat(data.map(i => i[item]))
          );
          this.form[item] = this.checkAttrAble[item][0];
        });
        resolve();
      });
    },
    //   初始化，根据id默认选中对应的报价详情
    init() {
      if (this.quotationDetail.quotationDetailList) {
        let data = this.quotationDetail.quotationDetailList.filter(
          i => i.id === this.id
        );
        let once = false;
        for (const key in this.form) {
          this.form[key] = data[0][key];
          // 用第一个值不为undefined的key去触发attrChange，计算可选项
          if (this.form[key] && !once) {
            this.attrChange(key);
            once = true;
          }
        }
      }
    }
  },
  created() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
::v-deep .ant-radio-group {
  .disabled {
    background-color: #d6d6d84d;
  }
  .ant-radio-button-wrapper {
    border-radius: 4px;
    padding: 0 10px;
    margin-bottom: 4px;
  }
  .ant-radio-button-wrapper::before {
    display: none;
  }
  .ant-radio-button-wrapper:not(:first-child) {
    border-left: 1px solid #d9d9d9;
  }
  .ant-radio-button-wrapper.ant-radio-button-wrapper-checked {
    border-left: 1px solid #4d65fd;
  }
  .ant-radio-button-wrapper:not(:last-child) {
    margin-right: 10px;
  }
}
::v-deep .ant-form-item-label label {
  font-size: 16px;
}
</style>
